import moment from 'moment';
moment.locale('zh-cn');

const defaultOptions = [
  moment().date(1),
  moment().add(-1, 'M').date(1),
  moment().add(-2, 'M').date(1),
  moment().add(-3, 'M').date(1),
  moment().add(-4, 'M').date(1)
];

const initialState = {
  records: [],
  options: defaultOptions,
  selected: defaultOptions[0].format('YYYY-MM-DD'),
}

export default function reducer(state = initialState, action) {

  // 查询
  if (action.type === '#query') {
    const records = [...action.payload.records];
    return { ...state, records, selected: action.payload.selected };
  }

  if (action.type === '#unauth'){
    return initialState
  }

  // 新建
  if (action.type === '#create'){
    const newRecord = {
      date: state.selected,
      time: '',
      desc: '',
      status: 2 // 0-编辑 1-保存 2-添加
    }

    const records = [...state.records, newRecord];
    return { ...state, records };
  }

  // 创建
  if (action.type === '#save') {
    let { index, record } = action.payload;
    state.records[index] = record;
    const records = [...state.records];
    return { ...state, records };
  }

  // 更新
  if (action.type === '#update') {
    let { index,record } = action.payload;
    console.log('record', record)
    state.records[index] = record;
    const records = [...state.records];
    return { ...state, records };
  }

  // 编辑
  if (action.type === '#edit') {
    const { index } = action.payload;
    state.records[index].status = 1;
    const records = [...state.records];
    return {
      ...state,
      records
    };
  }

  // 删除
  if (action.type === '#remove') {
    const { index } = action.payload;
    const records = state.records.filter((item, idx) => idx !== index);
    return { ...state, records };
  }

  // 取消
  if (action.type === '#cancel') {
    const { index } = action.payload;
    state.records[index].status = 0;
    const records = [...state.records];
    return { ...state, records };
  }

  return state
}
